// 列表、段落和按钮的引用
const list1 = document.querySelector('.input ul');
const list2 = document.querySelector('.output ul');
const para = document.querySelector('p');
const button = document.querySelector('button');

// 结果字符串
let result = '';

// 随机生成字符串函数
const randomChars = () => {
  let str = '';
  const choices = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()';
  for(let i = 0; i < 8; i += 1) {
    str += choices.charAt(Math.floor(Math.random() * choices.length));
  }
  return str;
};

let interval;
// 创建一个可读流对象
const stream = new ReadableStream({
  start(controller) {
    interval = setInterval(() => {
      let string = randomChars();

      // 添加这个字符串到新建流队列中
      controller.enqueue(string);

      // 在屏幕上显示出来
      let listItem = document.createElement('li');
      listItem.textContent = string;
      list1.appendChild(listItem);
    }, 1000);

    // 停止字符串生成按钮点击处理
    button.addEventListener('click', () => {
      clearInterval(interval);
      readString();
      controller.close(); // 关闭当前可读流
    })
  },
  pull(controller) {
    // 用不到
  },
  cancel() {
    // 当前流取消时，停止生成字符串
    clearInterval(interval);
  }
});

// 读取字符串
const readString = () => {
  const reader = stream.getReader();
  let charsReceived = 0;

  // read() 返回一个 Promise
  reader.read().then(function processText({done, value}) {
    // 参数是一个包含有两个参数的结果对象
    // done - 当读取完成时为 ture
    // value - 数据
    if (done) {
      console.log('String complete');
      para.textContent = result;
      return;
    }

    charsReceived += value.length;
    const chunk = value;
    let listItem = document.createElement('li');
    listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk;
    list2.appendChild(listItem);

    result += chunk;

    // 读取更多
    reader.read().then(processText);
  })
}